package com.hmyd.hmyd_android.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dialog.ConfirmInvestmentDialog;
import com.hmyd.hmyd_android.dialog.InvestmentSuccessDialog;
import com.hmyd.hmyd_android.dialog.NormalDialog;
import com.hmyd.hmyd_android.dialog.NormalDialogListener;
import com.hmyd.hmyd_android.dto.Capital;
import com.hmyd.hmyd_android.dto.InterestTime;
import com.hmyd.hmyd_android.utils.MyToast;
import com.hmyd.hmyd_android.utils.PreferencesUtils;
import com.hmyd.hmyd_android.utils.Utils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * 票惠宝（T+1）——确认
 * 
 * @author wangc
 * 
 */
@ContentView(R.layout.activity_back_confirm)
public class TicketsConfirmActivity extends BasicActivity {
	@ViewInject(R.id.home_title)
	public View home_title;
	@ViewInject(R.id.home_title_txt)
	public TextView home_title_txt;
	@ViewInject(R.id.home_right)
	public TextView home_right;

	@ViewInject(R.id.investment_name)
	private TextView investment_name;
	@ViewInject(R.id.investment_rate)
	private TextView investment_rate;
	@ViewInject(R.id.investment_time)
	private TextView investment_time;

	@ViewInject(R.id.personal_name)
	private TextView personal_name;
	@ViewInject(R.id.personal_tel)
	private TextView personal_tel;

	@ViewInject(R.id.investAmount)
	private EditText mInvestAmountEditText;
	@ViewInject(R.id.confirm_investment)
	private Button mConfirmInvestment;

	@ViewInject(R.id.interestReceive)
	private TextView interestReceive;
	@ViewInject(R.id.interestStart)
	private TextView interestStart;
	@ViewInject(R.id.expectreturn)
	private TextView expectreturn;

	// Bottom
	@ViewInject(R.id.pay_account)
	private TextView pay_account;
	@ViewInject(R.id.pay_amount)
	private TextView pay_amount;

	private final int CAPITAL = 2;
	private final int SUBMIT = 3;
	private final int BILL_TIME = 4;
	private final int AVAILABLE_AMOUNT = 5;

	private Capital mCapital;
	private InterestTime interestTime;
	private String mId;
	private double mMount;

	private String mBaseAmount;
	private String mMinInvestAmount;

	private String mTotalAmount;
	private String mPurchasedAmount;
	
	@ViewInject(R.id.back_info)
	private TextView back_info;
	@ViewInject(R.id.back_info_sev)
	private TextView back_info_sev;
	@ViewInject(R.id.hint)
	private TextView hint;
	@ViewInject(R.id.hint_content)
	private TextView hint_content;
	
	// 使用情况
	HashMap<String, Object> used = new HashMap<String, Object>();

	public static Intent getIntent(Context context, String id, String type, String name,
			String rate, String time, String timeUnit, double mount, long endTime,
			String itemStatus, String baseAmount, String minInvestAmount, String totalAmount,
			String purchasedAmount, String itemRateId, String dailyMInterest) {
		Intent intent = new Intent(context, TicketsConfirmActivity.class);
		intent.putExtra("id", id);
		intent.putExtra("type", type);
		intent.putExtra("name", name);
		intent.putExtra("rate", rate);
		intent.putExtra("time", time);
		intent.putExtra("timeUnit", timeUnit);
		intent.putExtra("mount", mount);
		intent.putExtra("endTime", endTime);
		intent.putExtra("itemStatus", itemStatus);

		intent.putExtra("baseAmount", baseAmount);
		intent.putExtra("minInvestAmount", minInvestAmount);

		intent.putExtra("totalAmount", totalAmount);
		intent.putExtra("purchasedAmount", purchasedAmount);
		intent.putExtra("itemRateId", itemRateId);
		intent.putExtra("dailyMInterest", dailyMInterest);

		return intent;
	}

	@OnClick({ R.id.confirm_investment, R.id.back_info })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.confirm_investment:

			if (isFastDoubleClick()) {
				return;
			}

			if (TextUtils.isEmpty(mInvestAmountEditText.getText().toString().trim())) {
				MyToast.showHMToast(this, false, "请输入投资金额");
				return;
			}
			
			Message msg = new Message();
			msg.what = 7;
			verificationHandler.sendMessage(msg);
			
			/*double realMount = 0;
			if (!TextUtils.isEmpty(mInvestAmountEditText.getText().toString().trim())) {
				realMount = Double.valueOf(mInvestAmountEditText.getText().toString().trim());
			}
			if (realMount < 0) {
				MyToast.showHMToast(this, false, "实际投资金额过小！");
				return;
			}

			RequestParams params = new RequestParams();
			params.addBodyParameter("itemId", mId);
			params.addBodyParameter("itemRateId", getIntent().getStringExtra("itemRateId"));
			params.addBodyParameter("investAmount", String.valueOf(realMount));

			mConfirmInvestment.setEnabled(false);
			mConfirmInvestment.setText("提交中...");

			onRequest(SUBMIT, UrlConstant.BILL_INVESTMENT, HttpMethod.POST, params);*/

			break;
		case R.id.back_info:
			Utils.jumpURL(TicketsConfirmActivity.this, AppBasic.app.billLinkUrl, "赎回说明", "", false);
			break;
		case R.id.back_info_sev:
			Utils.jumpURL(TicketsConfirmActivity.this, AppBasic.app.billLinkUrl, "赎回说明", "", false);
			break;

		default:
			break;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

		RequestParams params = new RequestParams();
		params.addBodyParameter("itemId", getIntent().getStringExtra("id"));
		onRequest(CAPITAL, UrlConstant.CAPITALDETAIL, HttpMethod.GET, null);
		onRequest(BILL_TIME, UrlConstant.BILL_TIME, HttpMethod.POST, null);
	}

	@Override
	public void onPostSuccess(int postId, String result) {
		Gson gson = new Gson();
		switch (postId) {
		case CAPITAL:
			java.lang.reflect.Type type = new TypeToken<Capital>() {
			}.getType();
			mCapital = gson.fromJson(result, type);

			if (mCapital != null) {
				mInvestAmountEditText.setHint("可用金额 " + mCapital.availableBalance);
			}

			break;
		case SUBMIT:
			InvestmentSuccessDialog cd = new InvestmentSuccessDialog(this,
					R.style.calculatorDialog, "投资\n成功");
			cd.show();
			break;
		case BILL_TIME:
			java.lang.reflect.Type type1 = new TypeToken<InterestTime>() {
			}.getType();
			interestTime = gson.fromJson(result, type1);

			interestStart.setText(interestTime.interestStart);
			interestReceive.setText(interestTime.interestReceive);
			break;
		case AVAILABLE_AMOUNT:
			mConfirmInvestment.setEnabled(true);
			try {
				JSONObject jsonObject = new JSONObject(result);
				expectreturn.setText(jsonObject.getString("dailyIncome"));
			} catch (JSONException e) {
				e.printStackTrace();
			}
			break;
		}
	}

	@Override
	public void onPostFailure(int postId, String msg) {
		setParams();
	}

	@Override
	protected void setParams() {
		home_title.setOnTouchListener(touch);
		home_title_txt.setText("确认投资");
		mInvestAmountEditText.addTextChangedListener(BenefitCalculations);
		mConfirmInvestment.setEnabled(false);

		mConfirmInvestment.setText("确认投资");
		mConfirmInvestment.setClickable(true);
		
		personal_name.setText(AppBasic.realName);
		personal_tel.setText(Utils.hidePhone(PreferencesUtils.getString(this,
				PreferencesUtils.USER_PHONE)));

		mBaseAmount = getIntent().getStringExtra("baseAmount");
		mMinInvestAmount = getIntent().getStringExtra("minInvestAmount");

		mTotalAmount = getIntent().getStringExtra("totalAmount");
		mPurchasedAmount = getIntent().getStringExtra("purchasedAmount");

		investment_name.setText(getIntent().getStringExtra("name"));
		investment_rate.setText(getIntent().getStringExtra("rate") + "%");

		mId = getIntent().getStringExtra("id");
		
		String period = getIntent().getStringExtra("time");
		String rate = getIntent().getStringExtra("rate")+"%";
		String rate_sp = rate.split("[+]")[0];
		
		if (period.equals("1")) {
			investment_time.setText("活期");
		} else if (period.equals("7")) {
			back_info.setVisibility(View.GONE);

			back_info_sev.setVisibility(View.VISIBLE);
			hint.setVisibility(View.VISIBLE);
			hint_content.setVisibility(View.VISIBLE);
			
			String investment_hint_content = getString(R.string.investment_hint_content);
			String msg = String.format(
					investment_hint_content, 
					period,
					rate,
					rate_sp
					);
			hint_content.setText(msg);
		} else {
			investment_time.setText(getIntent().getStringExtra("time")
					+ Utils.periodConversion(getIntent().getStringExtra("timeUnit")));
		}

	}

	@Override
	protected void leftButton() {
		AppBasic.getInstance().finishCurrentActivity();
	}

	@Override
	protected void rightButton() {

	}

	protected static long lastClickTime;

	/** 防止在短时间重复点击 **/
	public static boolean isFastDoubleClick() {
		long time = System.currentTimeMillis();
		long timeD = time - lastClickTime;
		if (0 < timeD && timeD < 800) {
			return true;
		}
		lastClickTime = time;
		return false;
	}

	/**
	 * 收益计算
	 */

	ArrayList<Timer> timerList = new ArrayList<Timer>();
	@SuppressLint("HandlerLeak")
	final Handler verificationHandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case 0:
				mMount = 0.0;
				pay_account.setText("0");
				break;
			case 1:
				MyToast.showHMToast(TicketsConfirmActivity.this, false, "投资金额格式有误");
				break;
			case 2:
				MyToast.showHMToast(TicketsConfirmActivity.this, false, "项目最低" + mMinInvestAmount
						+ "元起投");
				break;
			case 3:
				MyToast.showHMToast(TicketsConfirmActivity.this, false, "投资金额必须为" + mBaseAmount
						+ "的整数倍");
				break;
			case 4:
				MyToast.showHMToast(
						TicketsConfirmActivity.this,
						false,
						"项目当前剩余可投"
								+ (Double.valueOf(mTotalAmount) - Double.valueOf(mPurchasedAmount))
								+ "元");
				break;
			case 5:
				final NormalDialog cd = new NormalDialog(TicketsConfirmActivity.this,
						R.style.calculatorDialog, new NormalDialogListener() {
							@Override
							public void ok() {
								startActivity(new Intent(TicketsConfirmActivity.this,
										RechargeActivity.class));
								AppBasic.getInstance().finishCurrentActivity();
							}

							@Override
							public void cancle() {

							}

							@Override
							public void closed() {

							}

						}, TicketsConfirmActivity.this.getString(R.string.investment_tips),
						TicketsConfirmActivity.this.getString(R.string.investment_tips_content),
						"充值", "");
				cd.show();
				break;
			case 6:
				// 请求计算每日收益
				RequestParams params = new RequestParams();
				params.addBodyParameter("investAmount", String.valueOf(msg.obj));
				params.addBodyParameter("itemId", mId);
				params.addBodyParameter("itemRateId", getIntent().getStringExtra("itemRateId"));
				onRequest(AVAILABLE_AMOUNT, UrlConstant.AVAILABLE_AMOUNT, HttpMethod.POST, params);

				break;
			case 7:
				String rate = getIntent().getStringExtra("rate");
				rate = rate.contains("%") ? rate.replace("%", "") : rate;
				
				final ConfirmInvestmentDialog cd1 = new ConfirmInvestmentDialog(TicketsConfirmActivity.this,
						R.style.calculatorDialog, new NormalDialogListener() {
					@Override
					public void ok() {
						double realMount = 0;
						if (!TextUtils.isEmpty(mInvestAmountEditText.getText().toString().trim())) {
							realMount = Double.valueOf(mInvestAmountEditText.getText().toString().trim());
						}

						RequestParams params = new RequestParams();
						params.addBodyParameter("itemId", mId);
						params.addBodyParameter("itemRateId", getIntent().getStringExtra("itemRateId"));
						params.addBodyParameter("investAmount", String.valueOf(realMount));

						mConfirmInvestment.setEnabled(false);
						mConfirmInvestment.setText("提交中...");

						onRequest(SUBMIT, UrlConstant.BILL_INVESTMENT, HttpMethod.POST, params);
					}

					@Override
					public void cancle() {

					}

					@Override
					public void closed() {

					}

				},
				getIntent().getStringExtra("name"),
				rate + "%",
				getIntent().getStringExtra("time")+Utils.periodConversion(getIntent().getStringExtra("timeUnit")),
				mInvestAmountEditText.getText().toString().trim(),
				"", 
				"",
				pay_account.getText().toString().trim(),
				"确认投资",
				"取消投资");
				cd1.show();
				break;
			default:

				break;
			}
			super.handleMessage(msg);
		}
	};

	private TextWatcher BenefitCalculations = new TextWatcher() {

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {

		}

		@Override
		public void afterTextChanged(final Editable s) {
			for (Timer _timer : timerList) {
				_timer.cancel();
			}

			pay_account.setText(s.toString());

			Timer timer = new Timer();
			timerList.add(timer);

			timer.schedule(new TimerTask() {
				@Override
				public void run() {
					Message message = new Message();

					if (TextUtils.isEmpty(s.toString().trim())) {
						message.what = 0;
						verificationHandler.sendMessage(message);
						return;
					}

					try {
						Double.parseDouble(s.toString().trim());
					} catch (Exception e) {
						message.what = 1;
						verificationHandler.sendMessage(message);
						return;
					}

					try {
						double minInvestAmount = Double.parseDouble(mMinInvestAmount);
						double investAmount = Double.parseDouble(s.toString().trim());

						if (investAmount < minInvestAmount) {
							message.what = 2;
							verificationHandler.sendMessage(message);
							return;
						}

						double baseAmount = Double.parseDouble(mBaseAmount);

						if (investAmount % baseAmount != 0) {
							message.what = 3;
							verificationHandler.sendMessage(message);
							return;
						}

						double purchasedAmount = Double.valueOf(mPurchasedAmount);
						double totalAmount = Double.valueOf(mTotalAmount);

						if (investAmount > (totalAmount - purchasedAmount)) {
							message.what = 4;
							verificationHandler.sendMessage(message);
							return;
						}

					} catch (Exception e) {

					}

					if (mCapital != null
							&& Double.parseDouble(s.toString().trim()) > mCapital.availableBalance) {
						message.what = 5;
						verificationHandler.sendMessage(message);
						return;
					}

					message.what = 6;
					message.obj = s.toString().trim();
					verificationHandler.sendMessage(message);

				}
			}, 800);
		}

	};
}
